#!/usr/bin/perl

use strict;
use DBI;
use CGI;

use Crypt::PasswdMD5 qw(unix_md5_crypt);

# create_log.pl
#  - Jamie Stevens 2010-08-04

# This script creates a new entry in the 'log' table based on the
# information it is passed through HTML form post method. It then
# calls log_reader.pl with information about the newly created log
# entry.

my $in=CGI->new;

my %input=$in->Vars;

# make a webpage for debugging purposes
print $in->header;
print $in->start_html;

# encrypt the password (if one has been specified)
my @salt = ( '.', '/', 0 .. 9, 'A' .. 'Z', 'a' .. 'z' );
if ($input{"pwrd"}){
    my $encrypted=unix_md5_crypt($input{"pwrd"},gensalt(8));
    $input{"pwrd"}=$encrypted;
}

# debugging output onto webpage
my @expected_params=("project_code","observer",
		     "instrument","pwrd");

# do some error checking
if (!($input{"project_code"})){
    # can't proceed without a project code
    print $in->strong("Unable to create online log - a project ".
		      "code must be given");
    print $in->end_html;
    exit();
}

# open up a connection to the online_log database
my $dsn="dbi:Pg:dbname=online_log;host=localhost;port=5432";
my $db_user="logadd";
my $db_password="logadd";
my $dbh=DBI->connect($dsn,$db_user,$db_password,
		     {RaiseError => 1, AutoCommit => 1});

# make the entry query
my $make_log_query="INSERT INTO log (";
my $make_log_values="(";
my $added=0;
for (my $i=0;$i<=$#expected_params;$i++){
    if ($input{$expected_params[$i]}){
	if ($added>0){
	    $make_log_query.=",";
	    $make_log_values.=",";
	}
	if ($expected_params[$i] ne "pwrd"){
	    $make_log_query.=$expected_params[$i];
	} else {
	    $make_log_query.="password";
	}
	$make_log_values.="'".$input{$expected_params[$i]}."'";
	$added++;
    }
}
$make_log_query.=") VALUES ".$make_log_values.")";

# execute the query
my $make_log=$dbh->prepare($make_log_query);
$make_log->execute;

# get the ID of the last made entry
my $created_log_id=$dbh->last_insert_id(undef,undef,"log",undef);

$make_log->finish;

# sever the database connection
$dbh->disconnect;

# now make an invisible form that will get auto submitted, starting a
# new Perl script
print $in->start_form(-name => "return",
		      -method => "post",
		      -action => "log_reader.pl");

print $in->hidden(-name=>"log_id",-default=>$created_log_id);

print $in->end_form();

# now make the bit of Javascript that will auto-submit the form
print "<script language=\"JavaScript\" type=\"text/javascript\">".
    "document.return.submit();".
    "</script>";

print $in->end_html;

# uses global @salt to construct salt string of requested length
sub gensalt {
    my $count = shift;
    
    my $salt;
    for (1..$count) {
	$salt .= (@salt)[rand @salt];
    }
    
    return $salt;
}
